//
//  AccountTools.m
//  Yingzhi
//
//  Created by Maxwell Rose on 15/9/7.
//  Copyright (c) 2015年 yingzhi. All rights reserved.
//

#import "AccountTools.h"
#import "Reachability.h"
#import <CommonCrypto/CommonDigest.h>
#import <SSKeychain.h>
//#import "User.h"

NSString * const kService = @"ctcApp";
NSString * const kAccount = @"account";
NSString * const kUserID = @"userID";

NSString * const kUserName = @"name";
NSString * const kSchoolName = @"schoolName";
NSString * const kStudentNumber = @"studentNumber";
NSString * const kInSchoolYear = @"inSchoolYear";
NSString * const kSpecialty = @"specialty";
NSString * const kMail = @"mail";



@implementation AccountTools

//判断输入是否为空
+(BOOL)isEmpty:(NSString *) string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    if ([string isEqualToString:@"null"]) {
        return YES;
    }
    if ([string isEqualToString:@"(null)"]) {
        return YES;
    }
    if ([string isEqualToString:@""]) {
        return YES;
    }
    return NO;
}

+ (BOOL)validatePhoneNumber:(NSString *)string{
    
    NSString *phoneRegex = @"^(1[0-9])\\d{9}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:string];
}
+ (BOOL)validateEmail:(NSString *)string{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:string];
}


+ (BOOL)allIsNumber:(NSString *)string{
    NSString *numberRegex = @"^[0-9]*$";
    NSPredicate *numberTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegex];
    return [numberTest evaluateWithObject:string];
}

//身份证
+ (BOOL)isIdentificationCard:(NSString *)idCardString
{
    NSString * idCard = @"^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
    
    NSPredicate *regextestIDCard = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", idCard];
    return [regextestIDCard evaluateWithObject:idCardString];
    
}


+(BOOL)checkIDCard:(NSString *)value
{
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([value length] != 18) {
        return NO;
    }
    NSString *mmdd = @"(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8])))";
    NSString *leapMmdd = @"0229";
    NSString *year = @"(19|20)[0-9]{2}";
    NSString *leapYear = @"(19|20)(0[48]|[2468][048]|[13579][26])";
    NSString *yearMmdd = [NSString stringWithFormat:@"%@%@", year, mmdd];
    NSString *leapyearMmdd = [NSString stringWithFormat:@"%@%@", leapYear, leapMmdd];
    NSString *yyyyMmdd = [NSString stringWithFormat:@"((%@)|(%@)|(%@))", yearMmdd, leapyearMmdd, @"20000229"];
    NSString *area = @"(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|82|[7-9]1)[0-9]{4}";
    NSString *regex = [NSString stringWithFormat:@"%@%@%@", area, yyyyMmdd  , @"[0-9]{3}[0-9Xx]"];
    
    NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if (![regexTest evaluateWithObject:value]) {
        return NO;
    }
    int summary = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7
    + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9
    + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10
    + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5
    + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8
    + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4
    + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2
    + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6
    + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
    NSInteger remainder = summary % 11;
    NSString *checkBit = @"";
    NSString *checkString = @"10X98765432";
    checkBit = [checkString substringWithRange:NSMakeRange(remainder,1)];// 判断校验位
    return [checkBit isEqualToString:[[value substringWithRange:NSMakeRange(17,1)] uppercaseString]];
}


+ (BOOL)isConnectionAvailable{
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            break;
    }
    return isExistenceNetwork;
}

/**
 *  存储账号密码
 *
 *  @param account  账号名称
 *  @param password 账号密码
 */
+ (void)saveOwnAccount:(NSString *)account andPassword:(NSString *)password
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:account forKey:kAccount];
    [userDefaults synchronize];
    
    [SSKeychain setPassword:password forService:kService account:account];
}

/**
 *  获取存储的账号信息
 *
 *  @return @[account, password]
 */
+ (NSArray *)getOwnAccountAndPassword
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *account = [userDefaults objectForKey:kAccount];
    NSString *password = [SSKeychain passwordForService:kService account:account];
    
    if (account) {return @[account, password];}
    return nil;
}


+ (void)Savename:(NSString*)name
         schoolName:(NSString *)schoolName
       userHeadPhoto:(NSString *)userHeadPhoto
    studentCode:(NSString *)studentCode
     entryYear:(NSString *)entryYear
        profession:(NSString *)profession
             idNumber:(NSString *)idNumber
           email:(NSString *)email userType:(NSString*)userType

{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:name forKey:@"name"];
    [userDefaults setObject:schoolName forKey:@"schoolName"];
    [userDefaults setObject:userHeadPhoto forKey:@"userHeadPhoto"];
    [userDefaults setObject:studentCode forKey:@"studentCode"];
    [userDefaults setObject:entryYear forKey:@"entryYear"];
    [userDefaults setObject:profession forKey:@"profession"];
    [userDefaults setObject:idNumber forKey:@"idNumber"];
    [userDefaults setObject:email forKey:@"email"];
    [userDefaults setObject:userType forKey:@"userType"];
    [userDefaults synchronize];
}

+ (NSArray *)getUserInformation
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *name = [userDefaults objectForKey:@"name"]?[userDefaults objectForKey:@"name"]:@"";
    NSString *schoolName = [userDefaults objectForKey:@"schoolName"]?[userDefaults objectForKey:@"schoolName"]:@"";
    NSString *studentCode =[userDefaults objectForKey:@"studentCode"]?[userDefaults objectForKey:@"studentCode"]:@"";
    NSString *entryYear = [userDefaults objectForKey:@"entryYear"]?[userDefaults objectForKey:@"entryYear"]:@"";
    NSString *profession = [userDefaults objectForKey:@"profession"]?[userDefaults objectForKey:@"profession"]:@"";
    NSString *idNumber = [userDefaults objectForKey:@"idNumber"]?[userDefaults objectForKey:@"idNumber"]:@"";
    NSString *email = [userDefaults objectForKey:@"email"]?[userDefaults objectForKey:@"email"]:@"";
    
    NSString *userHeadPhoto = [userDefaults objectForKey:@"userHeadPhoto"]?[userDefaults objectForKey:@"userHeadPhoto"]:@"";
    NSString *userType = [userDefaults objectForKey:@"userType"]?[userDefaults objectForKey:@"userType"]:@"";
    return @[name, schoolName, userHeadPhoto, studentCode, entryYear, profession, idNumber,email,userType];
}

+ (NSArray *)getExamInformation
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *name = [userDefaults objectForKey:@"name"]?[userDefaults objectForKey:@"name"]:@"";
    NSString *schoolName = [userDefaults objectForKey:@"schoolName"]?[userDefaults objectForKey:@"schoolName"]:@"";
    NSString *studentCode =[userDefaults objectForKey:@"studentCode"]?[userDefaults objectForKey:@"studentCode"]:@"";
    NSString *entryYear = [userDefaults objectForKey:@"entryYear"]?[userDefaults objectForKey:@"entryYear"]:@"";
    NSString *profession = [userDefaults objectForKey:@"profession"]?[userDefaults objectForKey:@"profession"]:@"";
    NSString *idNumber = [userDefaults objectForKey:@"idNumber"]?[userDefaults objectForKey:@"idNumber"]:@"";
    NSString *email = [userDefaults objectForKey:@"email"]?[userDefaults objectForKey:@"email"]:@"";
    
    return @[name, schoolName, studentCode, entryYear, profession, idNumber,email];
    
}



/**
 *  登录之后将token存入本地方便以后接口调用
 *
 *  @param token 登录之后后台返回的一串字符
 */
+(void)saveUserToken:(NSString*)token
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:token forKey:@"token"];
    [userDefaults  synchronize];
}

+(NSString*)getUserToken
{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
}

//从NSUserDefaults中删除
+ (void)removeNSUserToken
{
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    [userDefaultes removeObjectForKey:@"token"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}

+(void)saveUserCd:(NSString*)UserCd
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:UserCd forKey:@"userCd"];
    [userDefaults  synchronize];
}

+(NSString*)getuserCd
{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"userCd"];
}
//获取用户类型
+(NSString *)getUserType
{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"userType"];
}
//从NSUserDefaults中删除
+ (void)removeNSuserCdn
{
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    [userDefaultes removeObjectForKey:@"userCd"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}


+(BOOL)isLogin
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *userToken = [userDefaults objectForKey:@"token"];
    if ([self isEmpty:userToken]) {
        return NO;
    }else{
        return YES;
    }
}

+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);// This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

+ (void)exitLogin
{
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"token"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userCd"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"name"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"schoolName"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userHeadPhoto"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"studentCode"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"entryYear"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"profession"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"idNumber"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"email"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userType"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


+ (NSString *)stringFromValue:(NSObject *)value
{
    
    
    if ([value isKindOfClass:[NSString class]])
    {
        return (NSString *)value;
    }
    else if ([value isKindOfClass:[NSNumber class]])
    {
        return [(NSNumber *)value stringValue];
    }
    else if ([value  isKindOfClass:[NSNull class]])
    {
        return @"";
    }
    else
    {
        return @"";
    }
}

+ (BOOL)validatePassWord:(NSString*)PassWord
{
    if (PassWord.length>32||PassWord.length<8) {
        return NO;
    }else{
        return YES;
    }
}

+ (BOOL)isUserName:(NSString *)name
{
    NSString *      regex = @"(^[\u4e00-\u9fa5])((?!.*\n).*$)";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:name];
}

+ (BOOL)UnlimitedLengthfChineseCharacters:(NSString *)name
{
    NSString *      regex = @"(^[\u4e00-\u9fa5]*$)";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:name];
}

@end
